<!-- specification component -->
<template>
  <v-card>
    <v-layout row>
      <v-flex xs3>
        <v-card>
          <v-card-title>选择分类，查看规格参数模板：</v-card-title>
          <v-divider></v-divider>
          <v-treeview
            :active.sync="active"
            :items="categoryList"
            item-key="id"
            :load-children="loadChildren"
            open-on-click
            return-object
            activatable
            transition
            dense
            @update:active="updateActive"
          >
            <template v-slot:prepend="{ item, open }">
              <v-icon v-if="!item.icon">{{ open ? 'mdi-folder-open' : 'mdi-folder' }}</v-icon>
              <v-icon v-else>{{ 'mdi-'+ item.icon }}</v-icon>
            </template>
          </v-treeview>
        </v-card>
      </v-flex>
      <v-flex xs9 class="px-1">
        <v-card color="basil" v-show="this.selected.id">
          <v-card-title class="text-center justify-center py-3">
            <p class="display-1 basil--text">规格参数</p>
          </v-card-title>
          <v-breadcrumbs :items="this.selected.items">
            <template v-slot:divider>
              <v-icon>mdi-chevron-right</v-icon>
            </template>
            <template v-slot:item="{ item }">
              <v-breadcrumbs-item>{{ item }}</v-breadcrumbs-item>
            </template>
          </v-breadcrumbs>
          <v-divider></v-divider>
          <v-tabs v-model="tab" grow>
            <v-tab v-for="item in items" :key="item.id" flat>{{ item.name }}</v-tab>
            <v-tabs-items v-model="tab">
              <v-tab-item v-for="item in items" :key="item.id">
                <v-card v-for="(item1,i) in item.params" :key="item1.id">
                  <v-card-title class="text-center">
                    <v-text-field
                      :ref="item1.name"
                      v-model="item1.name"
                      :solo="!item1.importable"
                      flat
                      append-icon="edit"
                      append-outer-icon="delete"
                      placeholder="请输入属性名称"
                      @click:append="editSpec(item1.name)"
                      @click:append-outer="deleteSpec(item.params, i)"
                    ></v-text-field>
                    <!-- <v-spacer></v-spacer> -->
                    <!-- <v-icon small class="mr-2" @click="editSpec(item1)">edit</v-icon> -->

                    <!-- <v-icon small @click="deleteSpec(item1)">delete</v-icon> -->
                  </v-card-title>
                  <v-card-text>
                    <v-layout row wrap class="mx-5 justify-space-between align-center">
                      <v-flex xs5>
                        <v-checkbox
                          v-model="item1.searchable"
                          :label="searchText"
                          color="primary"
                          hide-details
                        ></v-checkbox>
                      </v-flex>
                      <v-flex xs5>
                        <v-checkbox v-model="item1.generic" :label="globalText"></v-checkbox>
                      </v-flex>
                      <v-flex xs5>
                        <v-checkbox v-model="item1.numeric" :label="numericText"></v-checkbox>
                      </v-flex>
                      <v-flex xs12 v-if="item1.numeric">
                        <v-divider></v-divider>
                        <v-text-field v-model="item1.unit" suffix="单位" reverse class="px-12"></v-text-field>
                      </v-flex>
                      <v-flex xs12 v-if="item1.searchable> 0" class="px-2">
                        <v-divider></v-divider>可搜索过滤分组：
                        <v-layout row wrap class="justify-space-between">
                          <v-flex xs5 v-for="(s,i) in item1.options" :key="i">
                            <v-text-field
                              v-model="item1.options[i]"
                              hide-details
                              append-outer-icon="mdi-delete"
                              :suffix="item1.unit"
                              @click:append-outer="deleteSpecSegment(item1.options, i)"
                            ></v-text-field>
                          </v-flex>
                          <v-flex xs12>
                            <v-btn
                              small
                              fab
                              dark
                              color="primary"
                              class="my-3"
                              @click.stop="addSpecSegment(item1.options)"
                            >
                              <v-icon dark>mdi-plus</v-icon>
                            </v-btn>
                          </v-flex>
                        </v-layout>
                      </v-flex>
                    </v-layout>
                  </v-card-text>
                </v-card>
                <v-card-actions class="d-flex justify-space-around">
                  <v-spacer></v-spacer>
                  <v-btn class="primary" @click="addParam(item)">添加新属性</v-btn>
                </v-card-actions>
              </v-tab-item>
            </v-tabs-items>
          </v-tabs>
          <v-card-actions class="d-flex justify-space-around">
            <v-btn class="primary" @click="openAddGroupDialog">添加新分组</v-btn>
            <v-btn class="primary" @click="saveParams">保存面板参数</v-btn>
          </v-card-actions>
        </v-card>
      </v-flex>
    </v-layout>
    <v-dialog v-model="addedGroupDialog" max-width="400px">
      <v-card>
        <v-card-title class="primary">添加新分组</v-card-title>
        <v-card-text>
          <v-text-field v-model="newGroupName" placeholder="请输入分组名"></v-text-field>
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn @click="cancelAddGroup">取消</v-btn>
          <v-btn @click="addGroup">确认</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-card>
</template>

<script>
// const pause = ms => new Promise(resolve => setTimeout(resolve, ms));

export default {
  data() {
    return {
      open: [],
      active: [],
      categoryList: [],
      selected: {
        id: 0,
        items: []
      },
      specGroups: [],
      tab: null,
      items: [],
      searchText: "是否可搜索",
      globalText: "是否全局属性",
      numericText: "是否数值类型",
      addedGroupDialog: false,
      newGroupName: ""
    };
  },

  created() {
    this.getCategoryList(0);
  },
  computed: {},
  watch: {
    active: {
      deep: true,
      handler() {
        this.selected.id = this.active[0].id;
        const items = this.active[0]._name.split(",");
        items.map(el => {
          return {
            text: el
          };
        });
        this.selected.items = items;
        // console.log(this.selected);
      }
    }
  },
  methods: {
    // 获取分类列表
    getCategoryList(pid) {
      // console.log(item.id);
      this.axios
        .get("/item/category/list", {
          params: {
            pid: pid
          }
        })
        .then(resp => {
          if (resp.status != 200) {
            this.$message.error("获取分类列表失败");
          }
          resp.data.forEach(el => {
            el._name = el.name;
            if (el.isParent) {
              el.children = [];
            }
          });
          this.categoryList = resp.data;
        });
    },
    // 子分类懒加载
    loadChildren(item) {
      // console.log(item.isParent);
      // await pause(1500);
      return this.axios
        .get("/item/category/list", {
          params: {
            pid: item.id
          }
        })
        .then(resp => {
          if (resp.status != 200) {
            this.$message.error("获取分类列表失败");
          }
          resp.data.forEach(el => {
            el._name = item._name + "," + el.name;
            if (el.isParent) {
              el.children = [];
            }
          });
          item.children.push(...resp.data);
        });
    },
    // 当前激活改变触发
    updateActive(arr) {
      this.getSpecsByCid(arr[0].id);
    },
    // 获取分类ID对应的规格组
    getSpecsByCid(cid) {
      this.axios.get(`/item/spec/list/${cid}`).then(resp => {
        if (resp.status !== 200) {
          if (resp.status === 204) {
            this.$message.info("该分类没有规格组");
          } else {
            this.$message.error("获取规格组数据失败");
          }
          this.items = [];
          return;
        }
        // this.specGroups = resp.data;
        // console.log( resp.data);
        this.items = JSON.parse(resp.data);
        // this.items.forEach(el => {
        //   el.params.forEach(el1 => {
        //     el1.importable = false;
        //   });
        // });
        console.log(this.items);
      });
    },
    showAddedSpecGroupDialog() {},
    //修改规格组
    editSpecGroup(item) {
      console.log(item.id);
    },
    // 删除规格组
    deleteGroup(item) {
      console.log(item.name);
    },
    // 编辑属性
    editGroup(item) {
      console.log(item.name);
    },
    // 删除属性
    deleteSpec(items, i) {
      // console.log(items);
      // console.log(i);
      items.splice(i, 1);
    },
    // 编辑属性
    editSpec(item) {
      // console.log(item.name);
      // item.importable = true;
      // console.log(item);

      // console.log(this.$refs[item][0]);
      this.$refs[item][0].focus();
    },
    // 展开项
    expandItem(item, value) {
      console.log("item:", item);
      console.log("value:", value);
    },
    // 编辑组名或者属性名
    showInput(item) {
      item.importable = true;
    },
    // 删除属性搜索值
    deleteSpecSegment(items, i) {
      // console.log(items, i);
      items.splice(i, 1);
    },
    // 添加属性搜索值
    addSpecSegment(items) {
      // console.log(items);
      items.push("");
    },
    // 添加新属性
    addParam(item) {
      console.log(item);
      item.params.push({ options: [] });
    },
    // 打开添加新分组对话框
    openAddGroupDialog() {
      this.addedGroupDialog = true;
    },
    // 确认添加新分组
    addGroup() {
      const group = { name: this.newGroupName, params: [] };
      this.items.push(group);
      this.cancelAddGroup()
    },
    // 取消添加新分组
    cancelAddGroup() {
      this.addedGroupDialog = false;
      this.newGroupName = "";
    },
    // 参数保存到后台
    saveParams() {
      const data = JSON.parse(JSON.stringify(this.items));
      data.forEach(el => {
        el.params.forEach(ele => {
          // console.log(ele.options);

          ele.options = ele.options ? ele.options.join(",") : "";
        });
      });
      this.axios
        .post("/item/spec", { cid: this.active[0].id, specList: data })
        .then(resp => {
          // console.log(resp);
          if (resp.status !== 201) {
            this.$message.error('更新失败')
          }
          this.getSpecsByCid(this.active[0].id)
        });
    }
  }
};
</script>

<style lang='scss' scoped>
.v-treeview {
  padding-left: 5px;
}
.v-divider {
  margin-bottom: 10px;
}
.basil {
  background-color: #fffbe6 !important;
}
.basil--text {
  color: #356859 !important;
  font-size: 24px;
}
</style>